package edu.usx.server.service.impl;

import edu.usx.server.mapper.CategoryRoleMapper;
import edu.usx.server.pojo.Category;
import edu.usx.server.mapper.CategoryMapper;
import edu.usx.server.pojo.CategoryRole;
import edu.usx.server.pojo.RespBean;
import edu.usx.server.pojo.User;
import edu.usx.server.pojo.dto.CategoryDto;
import edu.usx.server.service.ICategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.models.auth.In;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import springfox.documentation.spi.service.contexts.SecurityContext;

import java.awt.*;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *s
 * @author Usx
 * @since 2024-07-18
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private CategoryRoleMapper categoryRoleMapper;
    /**
     * 根据用户id和权限查询分类
     * @return
     */
    @Override
    public List<Category> getCategoryByUserId() {
        int userId=((User) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId();
        Integer userRole=((User) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getRole_id();
        ValueOperations<String,Object> valueOperations=redisTemplate.opsForValue();
        //从redis获取菜单数据
        List<Category> categorys=(List<Category>) valueOperations.get("categorys_"+userId);
        //如果为空，就去数据库获取
        if(CollectionUtils.isEmpty(categorys)){
            categorys=categoryMapper.getCategoryByUserId(userId,userRole);
            //将数据设置到Redis中
            valueOperations.set("categorys_"+userId,categorys);
        }
        return categorys;

    }

    /**
     * 新建分类
     * @param categoryDto
     * @return
     */
    @Override
    @Transactional
    public RespBean addcategoryWithcid(CategoryDto categoryDto) {
        Category category = new Category();
        BeanUtils.copyProperties(categoryDto,category);
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        //默认status分类状态启用
        category.setStatus(1);
        List<CategoryRole> role=categoryDto.getRole();
        if (role==null|| role.size()==0){
            return RespBean.error("新建分类失败,未填写role数组");
        }
        String name =categoryMapper.selectByName(category.getName());
        if(name!=null){
        return RespBean.error("服务已存在请更换name");
        }
        categoryMapper.insertcategory(category);
        Integer cid=category.getId();



        if (role!=null && role.size()>0){
            role.forEach(roleflavor ->{
                roleflavor.setCid(cid);
                if(roleflavor.getUrole()==null){
                    //如果上传的数据urole不存在就默认设置为1
                    roleflavor.setUrole(1);
                }
            });
            System.out.println(role);
            categoryRoleMapper.insertBatch(role);

        }
        return RespBean.success("新建分类成功");

    }
    /**
     * 根据id修改分类
     * @param categoryDto
     * @return
     */
    @Override
    @Transactional
    public RespBean updateWithcid(CategoryDto categoryDto) {
//        基本信息
        Category category = new Category();
        BeanUtils.copyProperties(categoryDto,category);
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        categoryMapper.updatecategoryById(category);

        //删除原有的category_role数据再增加

        categoryRoleMapper.deletecategoryBatchId(categoryDto.getId());
        List<CategoryRole> role=categoryDto.getRole();
        if (role!=null && role.size()>0){
            role.forEach(roleflavor ->{
                roleflavor.setCid(categoryDto.getId());
                if(roleflavor.getUrole()==null){
                    //如果上传的数据urole不存在就默认设置为1
                    roleflavor.setUrole(1);
                }
            });
            System.out.println(role);
            categoryRoleMapper.insertBatch(role);
        }

        return RespBean.success("修改分类成功");
    }

    /**
     * 根据id删除分类
     * @param id
     * @return
     */
    @Override
    @Transactional
    public RespBean deleteWithcid(Integer id) {
            categoryMapper.deleteById(id);
            categoryRoleMapper.deletecategoryBatchId(id);
        return RespBean.success("删除分类成功");
    }
}
